<?php


// 小程序 appID 和 appSecret 获取 token
function getAccessToken($appid, $appsecret)
{
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
    $html = file_get_contents($url);
    $output = json_decode($html, true);
    $access_token = $output['access_token'];
    return $access_token;
}


function getOpenId($access_token){
    $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&lang=zh_CN";
    return file_get_contents($url);
}

//发送订阅消息
function sendSubscribeMessage($access_token, $touser, $template_id,$page,$content)
{

    //请求url
    $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;

    //发送内容
    $data = [] ;

    //接收者（用户）的 openid
    $data['touser'] = $touser ;

    //所需下发的订阅模板id
    $data['template_id'] = $template_id ;

    //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
    $data['page'] = $page ;

    //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
    $data['data'] = [
        "thing1" =>
            ['value' => '111'],
        //"thing3" =>
        //    ['value' => '222222'],

        "amount2" =>
            ['value' => "￥100"],

        //"phrase10"=>[
        //    'value' => '123456'
        //],
        //"name8"=>[
        //    'value' => '123456'
        //],
        //"amount12"=>[
        //    'value' => '123'
        //],
        //'date4'=>[
        //    'value'=>'123456'
        //],
        //'phone_number31'=>[
        //    'value'=>'123456'
        //]
    ];

    //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
    $data['miniprogram_state'] = 'developer' ;

    return curlPost($url,json_encode($data));
}

//发送post请求
function curlPost($url,$data)
{
    $ch = curl_init();
    $params[CURLOPT_URL] = $url;    //请求url地址
    $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
    $params[CURLOPT_SSL_VERIFYPEER] = false;
    $params[CURLOPT_SSL_VERIFYHOST] = false;
    $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
    $params[CURLOPT_POST] = true;
    $params[CURLOPT_POSTFIELDS] = $data;
    curl_setopt_array($ch, $params); //传入curl参数
    $content = curl_exec($ch); //执行
    curl_close($ch); //关闭连接
    return $content;
}